const User = require('../model/user.model');

class UserService {
  async createUser(user_name, password, is_admin) {
    // 插入数据
    const dbRes = await User.create({ user_name, password, is_admin });
    return dbRes.dataValues;
  }

  async getUserInfo({ id, user_name, password, is_admin }) {
    const whereOpt = {};
    id && Object.assign(whereOpt, { id });
    user_name && Object.assign(whereOpt, { user_name });
    password && Object.assign(whereOpt, { password });
    is_admin && Object.assign(whereOpt, { is_admin });
    const res = await User.findOne({
      attributes: ['id', 'user_name', 'password', 'is_admin'],
      where: whereOpt
    });
    return res ? res.dataValues : null;
  }

  async updateByIds({ id, user_name, password, is_admin }) {
    if (!id) {
      console.error('invalid value [id] 不能为空')
    }
    try {
      const whereOpt = { id };
      const userObj = {};
      user_name && Object.assign(userObj, { user_name });
      password && Object.assign(userObj, { password });
      is_admin && Object.assign(userObj, { is_admin });
      const res = await User.update(userObj, {
        where: whereOpt
      });
      return res[0] > 0;
    } catch (error) {
      console.error(error);
    }

  }
}


module.exports = new UserService();
